package com.gewu.pm.ui.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppAdapter;
import com.gewu.pm.bean.OrderBean;

import java.util.List;

/**
 * 代支付订单适配器（带倒计时功能）
 */
public class PaymentOrderAdapter extends AppAdapter<OrderBean> {

    private OnItemActionListener mListener;
    private Handler mCountdownHandler = new Handler(Looper.getMainLooper());
    private Runnable mCountdownRunnable;
    private int mTabType = 0;  // 0-先款后货，1-货到付款，2-账期非对公

    public PaymentOrderAdapter(Context context) {
        super(context);
    }

    public void setOnItemActionListener(OnItemActionListener listener) {
        mListener = listener;
    }

    public void setTabType(int tabType) {
        mTabType = tabType;
    }

    @Override
    public void setData(List<OrderBean> data) {
        super.setData(data);
        startCountdown();
    }

    /**
     * 启动倒计时
     */
    public void startCountdown() {
        stopCountdown();  // 先停止之前的
        
        mCountdownRunnable = new Runnable() {
            @Override
            public void run() {
                boolean hasCountdown = false;
                
                // 遍历所有数据，倒计时-1
                for (int i = 0; i < getCount(); i++) {
                    OrderBean order = getItem(i);
                    if (order.getCountdown() > 0) {
                        order.setCountdown(order.getCountdown() - 1);
                        // 局部刷新（只更新倒计时TextView）
                        notifyItemChanged(i, "countdown");
                        hasCountdown = true;
                    }
                }
                
                // 如果还有倒计时，继续
                if (hasCountdown) {
                    mCountdownHandler.postDelayed(this, 1000);
                }
            }
        };
        
        mCountdownHandler.postDelayed(mCountdownRunnable, 1000);
    }

    /**
     * 停止倒计时
     */
    public void stopCountdown() {
        if (mCountdownRunnable != null) {
            mCountdownHandler.removeCallbacks(mCountdownRunnable);
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new OrderViewHolder();
    }

    public void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull List<Object> payloads) {
        if (payloads.isEmpty()) {
            // 完整刷新
            onBindViewHolder(holder, position);
        } else {
            // 局部刷新（只更新倒计时）
            OrderBean order = getItem(position);
            OrderViewHolder vh = (OrderViewHolder) holder;
            vh.updateCountdown(order.getCountdown());
        }
    }

    private final class OrderViewHolder extends AppAdapter<?>.ViewHolder {

        private final TextView mTerminalNameView;
        private final ImageView mPhoneView;
        private final TextView mCreateTimeView;
        private final TextView mCreatorView;
        private final TextView mOrderNoView;
        private final TextView mVehicleCodeView;
        private final TextView mDeliveryMerchantView;
        private final TextView mSalespersonView;
        private final TextView mSalesRegionView;
        private final TextView mAmountLabelView;
        private final TextView mAmountView;
        private final TextView mCountdownView;
        private final TextView mPayButton;

        private OrderViewHolder() {
            super(R.layout.payment_order_item);
            mTerminalNameView = findViewById(R.id.tv_terminal_name);
            mPhoneView = findViewById(R.id.iv_phone);
            mCreateTimeView = findViewById(R.id.tv_create_time);
            mCreatorView = findViewById(R.id.tv_creator);
            mOrderNoView = findViewById(R.id.tv_order_no);
            mVehicleCodeView = findViewById(R.id.tv_vehicle_code);
            mDeliveryMerchantView = findViewById(R.id.tv_delivery_merchant);
            mSalespersonView = findViewById(R.id.tv_salesperson);
            mSalesRegionView = findViewById(R.id.tv_sales_region);
            mAmountLabelView = findViewById(R.id.tv_amount_label);
            mAmountView = findViewById(R.id.tv_amount);
            mCountdownView = findViewById(R.id.tv_countdown);
            mPayButton = findViewById(R.id.btn_pay);

            // 设置电话点击
            mPhoneView.setOnClickListener(v -> onPhoneClick(getViewHolderPosition()));
            
            // 设置去支付点击
            mPayButton.setOnClickListener(v -> onPayClick(getViewHolderPosition()));
        }

        @Override
        public void onBindView(int position) {
            OrderBean order = getItem(position);

            mTerminalNameView.setText(order.getTerminalName());
            mCreateTimeView.setText(order.getCreateTime());
            mCreatorView.setText(order.getCreator());
            mOrderNoView.setText(order.getOrderNo());
            mVehicleCodeView.setText(order.getVehicleCode());
            mDeliveryMerchantView.setText(order.getDeliveryMerchant());
            mSalespersonView.setText(order.getSalesperson());
            mSalesRegionView.setText(order.getSalesRegion());
            mAmountView.setText(order.getAmount());

            // 根据Tab类型设置金额标签
            String amountLabel = getAmountLabel();
            mAmountLabelView.setText(amountLabel);

            // 倒计时（只在先款后货Tab显示）
            if (mTabType == 0 && order.getCountdown() > 0) {
                mCountdownView.setVisibility(View.VISIBLE);
                updateCountdown(order.getCountdown());
            } else {
                mCountdownView.setVisibility(View.GONE);
            }

            // 去支付按钮状态（倒计时结束变灰）
            boolean canPay = order.getCountdown() > 0 || mTabType != 0;
            mPayButton.setEnabled(canPay);
        }

        /**
         * 更新倒计时显示（局部刷新）
         */
        public void updateCountdown(int seconds) {
            if (seconds > 0) {
                int minutes = seconds / 60;
                int secs = seconds % 60;
                mCountdownView.setText(String.format(getContext().getString(R.string.countdown_auto_cancel), minutes, secs));
                mCountdownView.setVisibility(View.VISIBLE);
                
                // 更新按钮状态
                mPayButton.setEnabled(true);
            } else {
                mCountdownView.setVisibility(View.GONE);
                // 倒计时结束，按钮变灰
                mPayButton.setEnabled(false);
            }
        }

        /**
         * 获取金额标签
         */
        private String getAmountLabel() {
            switch (mTabType) {
                case 0: return getContext().getString(R.string.order_amount_);
                case 1: return getContext().getString(R.string.delivery_amount_);
                case 2: return getContext().getString(R.string.account_amount_);
                default: return getContext().getString(R.string.order_amount_);
            }
        }

        @SingleClick
        private void onPhoneClick(int position) {
            if (mListener != null) {
                OrderBean order = getItem(position);
                mListener.onPhoneClick(order.getPhone());
            }
        }

        @SingleClick
        private void onPayClick(int position) {
            if (mListener != null) {
                OrderBean order = getItem(position);
                mListener.onPayClick(position, order);
            }
        }
    }

    /**
     * Item操作回调接口
     */
    public interface OnItemActionListener {
        /** 电话点击 */
        void onPhoneClick(String phone);
        
        /** 去支付点击 */
        void onPayClick(int position, OrderBean order);
    }
}

